import Vue from 'vue'
import App from './App'
import store from './store'
import * as filters from './filters'
import request from '@/common/SDK/request/request.js'
import '@/common/utils/sdk/sdk-h5.js'

const msg = (title, duration=1500, mask=false, icon='none')=>{

	if(Boolean(title) === false){
		return;
	}
	//#ifdef APP-PLUS
		plus.nativeUI.toast(title);
	//#endif
	//#ifndef APP-PLUS
		uni.showToast({
			title,
			duration,
			mask,
			icon
		});
	//#endif
}

const prePage = ()=>{
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}
const login = (token)=>{
	uni.setStorage({//缓存用户登陆状态
		key: 'userToken',
		data: {
			"token":token,
			"time":new Date()
		},
		success() {
			uni.reLaunch({
				url:"/pages/tab/index"
			})
		}
	})
}
const logout = ()=>{
	uni.removeStorage({
	    key: 'userToken'
	})
}
const hasLogin = ()=>{
	let userToken = uni.getStorageSync('userToken');
	if(!(userToken==""||userToken==null||userToken==undefined)){
		  return true;
	}
	return false;
}

Vue.config.productionTip = false
Vue.prototype.$store = store;
// 实例化Vue的filter
Object.keys(filters).forEach(k => Vue.filter(k, filters[k]))
Vue.prototype.$api = {msg,prePage,login,logout,hasLogin};
App.mpType = 'app'

import uView from 'uview-ui'
Vue.use(uView)

const app = new Vue({
	...App
})

// 全局配置
request.setConfig({
  // baseUrl: 'http://127.0.0.1:9001',
  baseUrl: 'http://www.dkkkgo.com:9001',
  dataType: 'json', // 可删除，默认为json
  responseType: 'text', // 可删除，默认为text
  // 设置请求头，支持所有请求头设置，也可不设置，去掉header就行
  header: {
    // 'token': 'token from global',
    // 'content-type': 'application/json'
  }
})

// 设置请求拦截器
request.interceptors.request(config => {
  // 配置参数和全局配置相同，此优先级最高，会覆盖在其他地方的相同配置参数
  let userToken = uni.getStorageSync('userToken');
  if(!(userToken==""||userToken==null||userToken==undefined)){
	  config.header.userToken = userToken.token;
  }
  return config;
})

request.interceptors.response(res => {
	if(typeof res.data !== "object"){
		res.data = JSON.parse(res.data);
	}
	// console.log(res);
	if(res.statusCode==200){
	  if(res.data.status==2000){
		  return res;
	  }else if(res.data.status==1004){
		  uni.reLaunch({
		  	url:"/pages/login/login"
		  })
		  return false;
	  }else if(res.data.status==1005){
		  logout();
		  uni.reLaunch({
		  	url:"/pages/login/login"
		  })
		  return false;
	  }else{
		  msg(res.data.msg);
		  return false;
	  }
	}
	msg("请求错误");
	return false;
})

Vue.prototype.$request = request;

app.$mount()
